package com.rlax.ccdemo.service.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rlax.ccdemo.service.user.dto.UpmsUserLoginDTO;
import com.rlax.ccdemo.service.user.entity.UpmsUser;
import com.rlax.ccdemo.service.user.mapper.UpmsUserMapper;
import com.rlax.ccdemo.service.user.service.UpmsUserService;
import com.rlax.corebin.core.exception.BusinessException;
import com.rlax.corebin.core.exception.code.ExceptionCode;
import com.rlax.corebin.jwt.model.AuthInfo;
import com.rlax.corebin.jwt.model.JwtUserInfo;
import com.rlax.corebin.jwt.util.TokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 用户表 服务实现类
 *
 * @author Rlax
 * @since 2021-03-31
 */
@Service
@RequiredArgsConstructor
public class UpmsUserServiceImpl extends ServiceImpl<UpmsUserMapper, UpmsUser> implements UpmsUserService {

    private final TokenUtil tokenUtil;

    @Override
    public AuthInfo login(UpmsUserLoginDTO loginDTO) {
        UpmsUser user = getOne(Wrappers.lambdaQuery(UpmsUser.class)
                .eq(UpmsUser::getUsername, loginDTO.getUsername())
                .eq(UpmsUser::getPassword, loginDTO.getPassword()));

        if (user == null) {
            throw BusinessException.wrap(ExceptionCode.USER_INVALID);
        }

        JwtUserInfo userInfo = new JwtUserInfo(user.getId(), user.getUsername(), user.getRealname());
        return tokenUtil.createAuthInfo(userInfo);
    }
}
